package com.novunda.platform.services;

import com.novunda.platform.common.utils.CacheUtils;
import com.novunda.platform.common.utils.DictUtils;
import com.novunda.platform.common.web.modal.Page;
import com.novunda.platform.entities.Dict;
import com.novunda.platform.entities.base.BaseEntity;
import com.novunda.platform.repositories.DictRepository;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * 字典服务
 * @author linfeng
 */
@Service
@Transactional
public class DictService extends BaseService {

    @Autowired
    private DictRepository dictRepository;

    public Dict get(Long id) {
        return dictRepository.findOne(id);
    }

    public Page<Dict> find(Page<Dict> page, Dict dict) {
        DetachedCriteria dc = dictRepository.createDetachedCriteria();
        if (StringUtils.isNotEmpty(dict.getType())){
            dc.add(Restrictions.eq("type", dict.getType()));
        }
        if (StringUtils.isNotEmpty(dict.getDescription())){
            dc.add(Restrictions.like("description", "%"+dict.getDescription()+"%"));
        }
        dc.add(Restrictions.eq(BaseEntity.DEL_FLAG, BaseEntity.DEL_FLAG_NORMAL));
        dc.addOrder(Order.asc("type")).addOrder(Order.asc("sort")).addOrder(Order.desc("id"));
        return dictRepository.find(page, dc);
    }

    public List<String> findTypeList(){
        return dictRepository.findTypeList();
    }

    @Transactional(readOnly = false)
    public void save(Dict dict) {
        dictRepository.save(dict);
        CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
    }

    @Transactional(readOnly = false)
    public void delete(Long id) {
        dictRepository.deleteById(id);
        CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
    }

    @Transactional(readOnly = false)
    public void saveMulit(List<Dict> dictList) {
        dictRepository.save(dictList);
        CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
    }

}
